import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
from python_ai.common.xcommon import *

target = cv.imread('../../../../../large_data/pic/football.jpg')
target = target[0:320, 0:450]
print(target.shape)
hsvt = cv.cvtColor(target, cv.COLOR_BGR2HSV)
roi = target[220:320, 10:170]
hsv = cv.cvtColor(roi, cv.COLOR_BGR2HSV)

cv.imshow("target", target)
cv.imshow("roi", roi)

# calculating object histogram
roihist = cv.calcHist([hsv], [0, 1], None, [180, 256], [0, 180, 0, 256])
print_numpy_ndarray_info(roihist, 'roihist')

# normalize histogram and apply backprojection
# 归一化：原始图像，结果图像，映射到结果图像中的最小值，最大值，归一化类型
# cv.NORM_MINMAX 对数组的所有值进行转化，使它们线性映射到最小值和最大值之间
# 归一化之后的直方图便于显示，归一化之后就成了0 到255 之间的数了。
cv.normalize(roihist, roihist, 0, 255, cv.NORM_MINMAX)
dst = cv.calcBackProject([hsvt], [0, 1], roihist, [0, 180, 0, 256], 1)
print_numpy_ndarray_info(dst, 'dst')
# Now convolute with circular disc
# 此处卷积可以把分散的点连在一起
disc = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
print("disc", disc)

dst_ori = dst.copy()
dst = cv.filter2D(dst, -1, disc)
dst_diff = cv.subtract(dst, dst_ori)
dst_cat = np.concatenate((dst_ori, dst, dst_diff), axis=1)
cv.imshow('dst ori,filtered,diff', dst_cat)
# threshold and binary AND
ret, thresh = cv.threshold(dst, 50, 255, 0)
# 别忘了是三通道图像，因此这里使用merge 变成3 通道
thresh = cv.merge((thresh, thresh, thresh))
# 按位操作
res = cv.bitwise_and(target, thresh)
res = np.hstack((target, thresh, res))

# cv.imwrite('res.jpg',res)
# 显示图像
cv.imshow('1', res)
cv.waitKey(0)

cv.destroyAllWindows()
plt.show()
